<?php
/**
 * Created by PhpStorm.
 * User: andrew郑
 * Date: 2017/10/13
 * Time: 15:35
 */

namespace app\index\controller;

class PushTransMsg
{
    private $appSecret = "appSecret";
    private $appId = "appId";//用户在华为开发者联盟申请的appId和appSecret（会员中心->我的产品，点击产品对应的Push服务，点击“移动应用详情”获取）
    private $tokenUrl = "https://login.vmall.com/oauth2/token"; //获取认证Token的URL
    private $apiUrl = "https://api.push.hicloud.com/pushsend.do"; //应用级消息下发API
    private $accessToken;//下发通知消息的认证Token
    private $tokenExpiredTime;  //accessToken的过期时间
    private $void;//参数组

    private function void($key, $value)
    {
        $this->void[$key] = $value;
    }

    public function main()
    {
        $this->refreshToken();
        return $this->sendPushMessage();
    }

    //获取下发通知消息的认证Token
    private function refreshToken()
    {
        $client_secret = $this->appSecret;
        $client_id = $this->appId;

        $this->void = null;

        $this->void(CURLOPT_POST, 1);
        $this->void(CURLOPT_HEADER, false);
        $this->void(CURLOPT_RETURNTRANSFER, true);
        $this->void(CURLOPT_CONNECTTIMEOUT, 5000);
        $this->void(CURLOPT_TIMEOUT, 5000);
        $this->void(CURLOPT_POSTFIELDS, 'grant_type=client_credentials&client_secret=' . $client_secret . '&client_id=' . $client_id);

        $response = HttpService::send($this->tokenUrl, $this->void);
        $obj = json_decode($response);
        $this->accessToken = $obj->access_token;
        $this->tokenExpiredTime = $this->msectime() + $obj->expires_in - 5 * 60 * 1000;
    }

    //发送Push消息
    private function sendPushMessage()
    {
        if ($this->tokenExpiredTime <= $this->msectime()) {
            $this->refreshToken();
        }
        /*PushManager.requestToken为客户端申请token的方法，可以调用多次以防止申请token失败*/
        /*PushToken不支持手动编写，需使用客户端的onToken方法获取*/
        $deviceTokens = array();//目标设备Token
        $deviceTokens[] = '12345678901234561234567890123456';
        $deviceTokens[] = '22345678901234561234567890123456';
        $deviceTokens[] = '32345678901234561234567890123456';


        $body = array();//仅通知栏消息需要设置标题和内容，透传消息key和value为用户自定义
        $body['key1'] = 'value1';//透传消息自定义body内容
        $body['key2'] = 'value2';//透传消息自定义body内容
        $body['key3'] = 'value3';//透传消息自定义body内容

        $msg = array();
        $msg['type'] = 1;//3: 通知栏消息，异步透传消息请根据接口文档设置
        $msg['body'] = $body;//通知栏消息body内容

        $hps = array();//华为PUSH消息总结构体
        $hps['msg'] = $msg;

        $payload = array();
        $payload['hps'] = $hps;

        $postBody = 'access_token=' . urlencode($this->accessToken) . '&nsp_svc=' . urlencode('openpush.message.api.send') . '&nsp_ts=' . (int)urlencode($this->msectime()/1000)
            . '&device_token_list=' . urlencode(json_encode($deviceTokens)) . '&payload=' . urlencode(json_encode($payload));
        $postUrl = $this->apiUrl . '?nsp_ctx=' . urlencode("{\"ver\":\"1\", \"appId\":\"" . $this->appId . "\"}");

        $this->void = null;

        $this->void(CURLOPT_POST, 1);
        $this->void(CURLOPT_HEADER, false);
        $this->void(CURLOPT_RETURNTRANSFER, 1);
        $this->void(CURLOPT_BINARYTRANSFER, 1);
        $this->void(CURLOPT_CONNECTTIMEOUT, 5000);
        $this->void(CURLOPT_TIMEOUT, 5000);
        $this->void(CURLOPT_POSTFIELDS, $postBody);


       return HttpService::send($postUrl, $this->void);

    }


    /**
     * 获取系统毫秒级时间戳
     * @return float
     */
    function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
}